package com.bndg.littletor.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View

class QwertyKeyboardView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val paint = Paint()
    private val keyLabels = arrayOf(
        "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P",
        "A", "S", "D", "F", "G", "H", "J", "K", "L",
        "Z", "X", "C", "V", "B", "N", "M"
    )

    private var rows = 3
    private var keysPerRow = intArrayOf(10, 9, 7) // 每行的按键数
    private lateinit var keyWidths: FloatArray
    private lateinit var keyHeights: FloatArray

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val width = width.toFloat()
        val height = height.toFloat()

        val keyHeight = height / rows
        val padding = 4f

        var index = 0

        for (row in 0 until rows) {
            val keysInRow = keysPerRow[row]
            val keyWidth = width / keysInRow

            for (col in 0 until keysInRow) {
                val left = col * keyWidth
                val top = row * keyHeight
                val right = left + keyWidth - padding
                val bottom = top + keyHeight - padding

                // Draw key background
                paint.color = Color.WHITE
                canvas.drawRect(left, top, right, bottom, paint)

                // Draw key text
                paint.color = Color.BLUE
                paint.textSize = keyHeight * 0.5f
                paint.textAlign = Paint.Align.CENTER

                val textX = (left + right) / 2
                val textY = top + (keyHeight - paint.descent() - paint.ascent()) / 2

                canvas.drawText(keyLabels[index++], textX, textY, paint)
            }
        }
    }

    override fun onMeasure(widthSpec: Int, heightSpec: Int) {
        val desiredWidth = suggestedMinimumWidth + paddingLeft + paddingRight
        val desiredHeight = (desiredWidth * 0.6).toInt() // 高度按比例设为宽度的 60%

        setMeasuredDimension(
            resolveSize(desiredWidth, widthSpec),
            resolveSize(desiredHeight, heightSpec)
        )
    }
}